<template>
    <div class="app-container">
        <!-- 搜索框 -->
        <el-form :model="userSearch" ref="queryForm" size="small" :inline="true" style="margin-left: 2px;">
            <el-form-item label="用户名称">
                <el-input placeholder="请输入用户名称" prefix-icon="el-icon-search" clearable v-model="userSearch.nickName" />
            </el-form-item>
            <el-form-item label="手机号">
                <el-input placeholder="请输入手机号码" prefix-icon="el-icon-search" clearable v-model="userSearch.phone" />
            </el-form-item>
            <el-form-item label="状态">
                <el-select placeholder="用户状态" clearable v-model="userSearch.status">
                    <el-option v-for="item in userStatusList" :key="item.id" :label="item.name" :value="item.value" />
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="getUserList(userSearch)">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetSearch()">重置</el-button>
            </el-form-item>
        </el-form>

        <!-- 主体 -->
        <el-table :data="userInfo" style="width: 100%">
            <el-table-column type="index" :index="1" label="序号" align="center" width="50">
            </el-table-column>
            <el-table-column prop="avatar" label="头像" align="center" width="100">
                <template slot-scope="scope">
                    <el-image style="width: 50px; height: 50px" :src="scope.row.avatar"></el-image>
                </template>
            </el-table-column>
            <el-table-column prop="nickName" label="用户名" align="center" width="100">
            </el-table-column>
            <el-table-column prop="account" label="用户账号" align="center" width="160">
            </el-table-column>
            <el-table-column prop="roleName" label="用户角色" align="center" width="100">
                <template slot-scope="scope">
                    <el-tag>{{ scope.row.roleName }}</el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="phone" label="手机号" align="center" width="160">
            </el-table-column>
            <el-table-column prop="loginIp" label="登入IP" align="center" width="120">
            </el-table-column>
            <el-table-column prop="updateTime" label="最后登入时间" align="center">
            </el-table-column>
            <el-table-column align="center" label="用户状态" width="80">
                <template slot-scope="scope">
                    <el-tooltip :content="scope.row.status == 0 ? '正常' : '冻结'" placement="top">
                        <el-switch v-model="scope.row.status" active-color="#13ce66" inactive-color="#ff4949"
                            :active-value="0" :inactive-value="1"
                            @change="changeUserStatus(scope.row.status, scope.row.id)">
                        </el-switch>
                    </el-tooltip>
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center">
                <template slot-scope="scope">
                    <el-button size="mini" type="warning" plain icon="el-icon-edit"
                        @click="handleUpdate(scope.row)">修改</el-button>
                    <el-button size="mini" type="danger" plain icon="el-icon-delete" slot="reference"
                        @click="handleDelete(scope.row.id)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <!-- 分页 -->
        <div class="block">
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="page"
                :page-sizes="[5, 10, 15, 20]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper"
                :total="total" align="center" background>
            </el-pagination>
        </div>

        <el-dialog title="修改用户" :visible.sync="dialogFormVisible">
            <el-form :model="user" ref="userInfo">
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="用户头像" label-width="120px">
                            <el-upload class="avatar-uploader" ref="upload" :action="uploadUrl" :show-file-list="false"
                                :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                                <img v-if="user.avatar" :src="user.avatar" class="avatar">
                                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                            </el-upload>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="用户名称" label-width="120px">
                            <el-input v-model="user.nickName" placeholder="请输入菜单名称" prop="menuName" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="用户角色" label-width="120px">
                            <el-radio-group v-model="user.roleId" size="medium" v-for="role in roleList" :key="role.id">
                                <el-radio :label="role.id" border style="margin-right: 30px;">{{ role.roleName }}</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="用户状态" label-width="120px">
                            <el-radio-group v-model="user.status" size="medium" v-for="status in userStatusList"
                                :key="status.id">
                                <el-radio :label="parseInt(status.value)" border style="margin-right: 30px;">{{ status.name
                                }}</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>

            <div slot="footer" class="dialog-footer">
                <el-button @click="cancelFrom()">取 消</el-button>
                <el-button type="primary" @click="submitFrom()">确 定</el-button>
            </div>
        </el-dialog>

    </div>
</template>

<script>
import { mapGetters } from 'vuex'
import user from '@/api/user'
import dict from "@/api/dict"
import role from '@/api/role'
import fileApi from '@/api/file'
export default {
    data() {
        return {
            dialogFormVisible: false, // 对话框开关
            roleList: [], // 角色信息列表
            userSearch: {}, // 用户搜索
            userInfo: [], // 用户信息列表
            user: {}, // 用户类
            userStatusList: [], // 用户状态列表
            total: 0, // 用户总数
            pageSize: 5, // 每页总数
            page: 1, // 当前页
            uploadUrl: 'http://127.0.0.1:8203/local/upload',
            oldAvatar: ''
        }
    },
    computed: {
        ...mapGetters(
            ['userid']
        )
    },
    methods: {
        // 取消表单提交
        cancelFrom() {
            // 如果取消表单，则删除 oss 中新上传的头像
            // fileApi.deleteAvatarOss(this.user.avatar.split('avatar/')[1]).then(res => { })
            // 并把老头像赋值给用户头像
            this.user.avatar = this.oldAvatar
            this.dialogFormVisible = false
        },
        handleAvatarSuccess(res, file) {
            // 上传 oss 成功后，将原头像设置成老头像
            this.oldAvatar = this.user.avatar
            // 将上传成功的头像设置成新头像
            this.user.avatar = res.data
            console.log(res)
            this.$message.success("上传成功！")
        },
        beforeAvatarUpload(file) {
            if (this.userid !== 1) {
                this.$message.error('权限不足');
                return false
            }
            const isJPG = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/gif';
            const isLt2M = file.size / 1024 / 1024 < 2;

            if (!isJPG) {
                this.$message.error('上传头像图片只能是 JPG/png/gif 格式!');
            }
            if (!isLt2M) {
                this.$message.error('上传头像图片大小不能超过 2MB!');
            }
            return isJPG && isLt2M;
        },
        // 获取角色信息
        getRoleAll() {
            role.getRoleAll().then(res => {
                this.roleList = res.data
            })
        },
        // 修改用户信息
        handleUpdate(userInfo) {
            this.dialogFormVisible = true
            this.user = userInfo
        },
        handleDelete(id) {
            user.deleteUserById(id).then(res => {
                this.$message({
                    message: '删除成功',
                    type: 'success'
                });
                this.getUserInfo(this.page, this.pageSize);
            })
        },
        // 提交表单信息
        submitFrom() {
            this.$refs["userInfo"].validate(valid => {
                if (valid) {
                    this.$refs.upload.submit();
                    user.updateUserById(this.user).then(res => {
                        this.$message({
                            message: '修改成功',
                            type: 'success'
                        });
                        this.dialogFormVisible = false
                        // 如果修改的用户id为当前登入id,则刷新state
                        if (this.user.id === this.userid) {
                            this.$store.commit("user/SET_NAME", this.user.nickName)
                            this.$store.commit("user/SET_AVATAR", this.user.avatar)
                        }
                    })
                    // 提交表单成功后，删除老头像
                    // fileApi.deleteAvatarOss(this.oldAvatar.split('avatar/')[1]).then(res => { })
                    this.getUserInfo(this.page, this.pageSize);
                }
            })
        },
        // 获取用户信息
        getUserInfo(page, pageSize, userSearch) {
            user.getUserById(page, pageSize, userSearch).then(
                res => {
                    this.userInfo = res.data.rows
                    this.total = res.data.total
                }
            )
        },
        getUserList(userSearch) {
            this.getUserInfo(this.page, this.pageSize, userSearch)
        },
        resetSearch() {
            this.userSearch = {}
            this.getUserInfo(0, this.pageSize);
        },
        // 用户状态
        getStatus(code) {
            dict.getBlogDictByCode(code).then(res => {
                this.userStatusList = res.data
            })
        },
        // 修改用户状态
        changeUserStatus(status, id) {
            user.changeUserStatus(status, id).then(res => {
                this.$message({
                    message: '修改成功',
                    type: 'success'
                });
            })
            this.getUserInfo(this.page, this.pageSize);
        },
        // 获取当前页有几条数据
        handleSizeChange(val) {
            this.pageSize = val
            this.getUserInfo(this.page, this.pageSize);
        },
        // 获取当前页
        handleCurrentChange(val) {
            this.page = val
            this.getUserInfo(this.page, this.pageSize);
        }
    },

    mounted() {
        this.getUserInfo(0, this.pageSize);
        this.getStatus('sys_normal_disable');
        this.getRoleAll();
    }
}
</script>

<style scoped>
::v-deep th {
    background-color: #f8f8f9;
}

.block {
    margin-top: 10px;
}

::v-deep .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

::v-deep .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
}

.avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>